#!/usr/bin/env python
# -*-coding:UTF-8 -*-
'''
@Project ：19-xpath站长素材.py
@File：53-selenium简书.py
@Author ：文非
@Date：2021/3/1713:54
@Require： # 获取简书
'''
from selenium import webdriver
import time
from PIL import Image
from chaojiying import Chaojiying_Client
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
# 实例化一个浏览器对象
brow = webdriver.Chrome(executable_path="./chromedriver.exe")
# 指定url
url = "https://www.jianshu.com/sign_in"
# 对登陆页面进行登录请求
brow.get(url)
# 寻找对应的标签
user = brow.find_element_by_id("session_email_or_mobile_number")
user.send_keys("13476923553")
time.sleep(1)
pwd = brow.find_element_by_id("session_password")
pwd.send_keys("zwwlx1013")
time.sleep(1)
login_btn = brow.find_element_by_id("sign-in-form-submit-btn")
login_btn.click()
# 截取整个页面
brow.save_screenshot("jianshu.png")
# 截取验证码图片
code_element = EC.presence_of_element_located((By.CLASS_NAME, 'geetest_widget'))
# 确定验证码图片对应的左上角和右下角的坐标（裁剪的区域就确定）
# 验证码图片左上角的坐标 x,y
code_location = code_element.location
print("location",code_location)
# 验证码标签的长和宽
size = code_element.size
print("size",size)
# 动作链点击确认
rangle = (
int(code_location['x']), int(code_location['y']), int(code_location['x'] + size['width']), int(code_location['y'] + size['height']))
#至此验证码图片区域就确定下来了

# 然后将此验证码的区域裁剪下来导入模块PIL
img = Image.open("./jianshu.png")
code_img_name = "./js_code.png"
# crop 方法 根据指定区域进行图片裁剪
frame = img.crop(rangle)
# 将图片按指定的名字保存
frame.save(code_img_name)

# 将验证码图片提交给第三方平台进行识别
chaojiying = Chaojiying_Client('zwwlx1013', 'zwwlx1013', '	914117')	#用户中心>>软件ID 生成一个替换 96001
im = open('code.png', 'rb').read()													#本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
print(chaojiying.PostPic(im, 9004)['pic_str'])
pic_string = chaojiying.PostPic(im, 9004)['pic_str']

# 使用动作链进行点击
all_list = [] # 存储即将被点击的点的坐标 形式 [,] 也可以是 [[],[],[]]
if "|" in pic_string:
    list_1 = pic_string.split("|")
    count_1 = len(list_1)
    print(count_1)
    for i in range(count_1):
        xy_list = []
        x = int(list_1[i].split(',')[0])
        y = int(list_1[i].split(",")[1])
        xy_list.append(x)
        xy_list.append(y)
        all_list.append(xy_list)
else:
    x = int(pic_string.split(',')[0])
    y = int(pic_string.split(",")[1])
    xy_list = []
    xy_list.append(x)
    xy_list.append(y)
    all_list.append(xy_list)
print(all_list)

# 遍历列表,使用动作链对每一个列表元素对应的x，y指定位置进行点击操作
for l in all_list:
    x = l[0]
    y = l[1]
    # 这个列表返回的坐标是相对于验证码的左上角来确定的 在点击时应该以整个门户网站照片为参数 所以应该先定位到验证码图片元素所在的模块中
    # 使用move_to_element_with_offset()这个方法,第一个参数为验证码
    ActionChains(brow).move_to_element_with_offset(code_element, x, y).click().perform()
    time.sleep(0.5)
brow.find_element_by_id("username").send_keys("13476923553")
time.sleep(2)
brow.find_element_by_id("password").send_keys("zwwlx1013")
time.sleep(2)
brow.find_element_by_id("loginSub").click()
time.sleep(3)
